Self-Driving Car Engineer Nanodegree

Deep Learning

Project: Build a Traffic Sign Recognition Classifier

In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.

Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.

The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.

Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.


Step 0: Load The Data

In [186]:
# Load pickled data
import pickle

data_path = '/notebooks/traffic-signs-data'

training_file = ('%s/train.p' % data_path)
validation_file= ('%s/valid.p' % data_path)
testing_file = ('%s/test.p' % data_path)

with open(training_file, mode='rb') as f:
    train = pickle.load(f)
with open(validation_file, mode='rb') as f:
    valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
    test = pickle.load(f)
    
X_train, y_train, sizes_train = train['features'], train['labels'], train['sizes']
X_valid, y_valid, sizes_valid = valid['features'], valid['labels'], valid['sizes']
X_test, y_test, sizes_test = test['features'], test['labels'], test['sizes']


import pandas.io.parsers as pparsers

signnames = pparsers.read_csv("signnames.csv").values[:, 1]

Step 1: Dataset Summary & Exploration

The pickled data is a dictionary with 4 key/value pairs:

  • 'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).
  • 'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.
  • 'sizes' is a list containing tuples, (width, height) representing the the original width and height the image.
  • 'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGES

Complete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.

Provide a Basic Summary of the Data Set Using Python, Numpy and/or Pandas

In [216]:
### Replace each question mark with the appropriate value. 
### Use python, pandas or numpy methods rather than hard coding the results
import numpy as np


# TODO: Number of training examples
n_train = X_train.shape[0]

# Number of validation examples
n_valid = X_valid.shape[0]

# TODO: Number of testing examples.
n_test = X_test.shape[0]

# TODO: What's the shape of an traffic sign image?
image_shape = X_train[0].shape

# TODO: How many unique classes/labels there are in the dataset.
nr_classes = len(np.unique(y_train))

print("Number of training examples =", n_train)
print("Number of validation examples =", n_valid)
print("Number of testing examples =", n_test)
print("Image data shape =", image_shape)
print("Number of classes =", nr_classes)
Number of training examples = 34799
Number of validation examples = 4410
Number of testing examples = 12630
Image data shape = (32, 32, 3)
Number of classes = 43

Include an exploratory visualization of the dataset

Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.

The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.

NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections.

In [188]:
### Data exploration visualization code goes here.
### Feel free to use as many code cells as needed.
import matplotlib.pyplot as plt
# Visualizations will be shown in the notebook.
%matplotlib inline

import scipy.ndimage as ndimage
import math

plt.rcdefaults()

def plotCountsPerClass(labels, axis):
    classes = np.sort(np.unique(labels))
    x_pos = np.arange(len(classes))

    def count(x):
        return len(labels[labels == x])

    numbers_per_class = [count(x) for x in classes]
    axis.bar(x_pos, numbers_per_class, align='center', color='green', ecolor='black')

def plotSizes(sizes, labels, tag):
    classes = np.sort(np.unique(labels))
    width_average = []
    width_limit = []

    height_average = []
    height_limit = []

    for class_idx in classes:
        idxs = np.argwhere(labels == class_idx).flatten()
        class_sizes = sizes[idxs]
        class_widths = [x[0] for x in class_sizes]
        class_heights = [x[1] for x in class_sizes]
        class_width_average = np.ceil(np.mean(class_widths))
        class_width_max = np.ceil(np.min(class_widths))
        class_width_min = np.ceil(np.max(class_widths))
        width_average.extend([class_width_average])
        width_limit.extend([np.max([class_width_max - class_width_average, class_width_average - class_width_min])])
        
        class_height_average = np.ceil(np.mean(class_heights))
        class_height_max = np.ceil(np.min(class_heights))
        class_height_min = np.ceil(np.max(class_heights))
        height_average.extend([class_height_average])
        height_limit.extend([np.max([class_height_max - class_height_average, class_height_average - class_height_min])])

    x_pos = np.arange(len(classes))
    
    sizes_figure = plt.figure(figsize = (15, 5))
    axis_width = sizes_figure.add_subplot(1, 2, 1)
    axis_width.bar(x_pos, width_average, yerr=width_limit, align='center', color='green', ecolor='black')
    plt.title('Width per class: %s' % tag)
    plt.xlabel('Classes')
    plt.ylabel('Width')
    
    axis_height = sizes_figure.add_subplot(1, 2, 2)
    axis_height.bar(x_pos, height_average, yerr=height_limit, align='center', color='green', ecolor='black')
    plt.title('Height per class: %s' % tag)
    plt.xlabel('Classes')
    plt.ylabel('Height')
    plt.show()

def plotRandomSamplesfromClass(images, labels, class_idx, nr_samples):
    print ('Class: %s: %s' % (class_idx, signnames[class_idx]))
    idxs = np.argwhere(labels == class_idx).flatten()
    selected_indices = np.random.choice(idxs, nr_samples)
    selected_images = images[selected_indices]
    fig = plt.figure(figsize = (10, 1))
    for (i, image) in enumerate(selected_images):
        axis = fig.add_subplot(1, 10, i + 1, xticks=[], yticks=[])
        axis.imshow(image)
    plt.show()
    
def plotRandomSamples(images, labels, nr_samples):
    classes = np.sort(np.unique(labels))
    for class_idx in classes:
        plotRandomSamplesfromClass(images, labels, class_idx, nr_samples)

Number of samples per sign class:

In [189]:
samples_figure = plt.figure(figsize = (15, 5))

axis = samples_figure.add_subplot(1, 3, 1)
plotCountsPerClass(y_train, axis)
plt.title('Samples per class: training')
plt.xlabel('Classes')
plt.ylabel('Samples')

axis = samples_figure.add_subplot(1, 3, 2)
plotCountsPerClass(y_valid, axis)
plt.title('Samples per class: validation')
plt.xlabel('Classes')
plt.ylabel('Samples')

axis = samples_figure.add_subplot(1, 3, 3)
plotCountsPerClass(y_test, axis)
plt.title('Samples per class: test')
plt.xlabel('Classes')
plt.ylabel('Samples')

plt.show()

Original sizes:

In [190]:
plotSizes(sizes_train, y_train, 'train')
plotSizes(sizes_valid, y_valid, 'validation')
plotSizes(sizes_test, y_test, 'test')

Samples of images per class:

In [191]:
plotRandomSamples(X_train, y_train, 10)
Class: 0: Speed limit (20km/h)
Class: 1: Speed limit (30km/h)
Class: 2: Speed limit (50km/h)
Class: 3: Speed limit (60km/h)
Class: 4: Speed limit (70km/h)
Class: 5: Speed limit (80km/h)
Class: 6: End of speed limit (80km/h)
Class: 7: Speed limit (100km/h)
Class: 8: Speed limit (120km/h)
Class: 9: No passing
Class: 10: No passing for vehicles over 3.5 metric tons
Class: 11: Right-of-way at the next intersection
Class: 12: Priority road
Class: 13: Yield
Class: 14: Stop
Class: 15: No vehicles
Class: 16: Vehicles over 3.5 metric tons prohibited
Class: 17: No entry
Class: 18: General caution
Class: 19: Dangerous curve to the left
Class: 20: Dangerous curve to the right
Class: 21: Double curve
Class: 22: Bumpy road
Class: 23: Slippery road
Class: 24: Road narrows on the right
Class: 25: Road work
Class: 26: Traffic signals
Class: 27: Pedestrians
Class: 28: Children crossing
Class: 29: Bicycles crossing
Class: 30: Beware of ice/snow
Class: 31: Wild animals crossing
Class: 32: End of all speed and passing limits
Class: 33: Turn right ahead
Class: 34: Turn left ahead
Class: 35: Ahead only
Class: 36: Go straight or right
Class: 37: Go straight or left
Class: 38: Keep right
Class: 39: Keep left
Class: 40: Roundabout mandatory
Class: 41: End of no passing
Class: 42: End of no passing by vehicles over 3.5 metric tons

Step 2: Design and Test a Model Architecture

Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.

There are various aspects to consider when thinking about this problem:

  • Neural network architecture
  • Play around preprocessing techniques (normalization, rgb to grayscale, etc)
  • Number of examples per label (some have more than others).
  • Generate fake data.

Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.

NOTE: The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!

Pre-process the Data Set (normalization, grayscale, etc.)

Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.

Image processing functions:

In [192]:
### Preprocess the data here. Preprocessing steps could include normalization, converting to grayscale, etc.
### Feel free to use as many code cells as needed.

import cv2

def applyAffineTransformationLeft(image):
    rows,cols,ch = image.shape
    pts1 = np.float32([[10,10],[20,10],[10,20]])
    pts2 = np.float32([[8,12],[20,10],[12,22]])
    M = cv2.getAffineTransform(pts1,pts2)
    dst = cv2.warpAffine(image,M,(cols,rows))
    return dst

def applyAffineTransformationRight(image):
    rows,cols,ch = image.shape
    pts1 = np.float32([[10,10],[20,20],[10,20]])
    pts2 = np.float32([[10,10],[18,22],[12,22]])
    M = cv2.getAffineTransform(pts1,pts2)
    dst = cv2.warpAffine(image,M,(cols,rows))
    return dst

def applyRotation(image, angle):
    rows,cols,ch = image.shape
    M = cv2.getRotationMatrix2D((cols/2,rows/2),angle,1)
    dst = cv2.warpAffine(image,M,(cols,rows))
    return dst

def applyGrayScale(image):
    dst = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    return dst

def applyNormalization(image):
    img = np.copy(image)
    mean = np.mean(img, axis = (0, 1))
    img = img - mean
    img = img / mean
    return img
    

Demonstrate effect of augmentation for small number of samples:

In [193]:
def plotRandomSamplesWithTransformed(images, numberOfSamples):
    selectedIndices = np.random.choice(images.shape[0], numberOfSamples)
    selectedImages = images[selectedIndices]
    
    for (i, image) in enumerate(selectedImages):
        fig = plt.figure(figsize = (10, 1))
        axis = fig.add_subplot(1, 6, 1, xticks=[], yticks=[])
        axis.imshow(image)
        axis = fig.add_subplot(1, 6, 2, xticks=[], yticks=[])
        axis.imshow(applyAffineTransformationLeft(image))
        axis = fig.add_subplot(1, 6, 3, xticks=[], yticks=[])
        axis.imshow(applyAffineTransformationRight(image))
        axis = fig.add_subplot(1, 6, 4, xticks=[], yticks=[])
        axis.imshow(applyRotation(image, 15))
        axis = fig.add_subplot(1, 6, 5, xticks=[], yticks=[])
        axis.imshow(applyRotation(image, -15))
        axis = fig.add_subplot(1, 6, 6, xticks=[], yticks=[])
        axis.imshow(applyGrayScale(image))
        plt.show()

plotRandomSamplesWithTransformed(X_train, 5)

Data set augmentation:

In [194]:
def augmentDataSet(images, labels):
    # For each image we will generate:
    #   - original image
    #   - affine transformation to left
    #   - affine transformation to right
    #   - rotation 15 degrees clock-wise
    #   - rotation 15 degrees counter-clock-wise
    augmentation_functions = [
        lambda x: x,
        applyAffineTransformationLeft,
        applyAffineTransformationRight,
        lambda x: applyRotation(x, 15),
        lambda x: applyRotation(x, -15),
    ]
    
    augmented_images = []
    augmented_labels = []
    
    for (image, label) in zip(images, labels):
        augmented_images.extend(map(lambda fn: fn(image), augmentation_functions))
        augmented_labels.extend([label for number in range(len(augmentation_functions))])

    return (np.asarray(augmented_images), np.asarray(augmented_labels))

def preprocessDataSet(images):
    preprocessing_functions = [
        applyNormalization,
    ]
    def processImage(img):
        for fn in preprocessing_functions:
            img = fn(img)
        return img

    processed_images = []
    processed_images.extend(map(processImage, images))
    return np.asarray(processed_images)

Demonstrate samples from augmented data set:

In [195]:
data, labels =  augmentDataSet(X_train, y_train)
plotRandomSamples(data, labels, 10)
Class: 0: Speed limit (20km/h)
Class: 1: Speed limit (30km/h)
Class: 2: Speed limit (50km/h)
Class: 3: Speed limit (60km/h)
Class: 4: Speed limit (70km/h)
Class: 5: Speed limit (80km/h)
Class: 6: End of speed limit (80km/h)
Class: 7: Speed limit (100km/h)
Class: 8: Speed limit (120km/h)
Class: 9: No passing
Class: 10: No passing for vehicles over 3.5 metric tons
Class: 11: Right-of-way at the next intersection
Class: 12: Priority road
Class: 13: Yield
Class: 14: Stop
Class: 15: No vehicles
Class: 16: Vehicles over 3.5 metric tons prohibited
Class: 17: No entry
Class: 18: General caution
Class: 19: Dangerous curve to the left
Class: 20: Dangerous curve to the right
Class: 21: Double curve
Class: 22: Bumpy road
Class: 23: Slippery road
Class: 24: Road narrows on the right
Class: 25: Road work
Class: 26: Traffic signals
Class: 27: Pedestrians
Class: 28: Children crossing
Class: 29: Bicycles crossing
Class: 30: Beware of ice/snow
Class: 31: Wild animals crossing
Class: 32: End of all speed and passing limits
Class: 33: Turn right ahead
Class: 34: Turn left ahead
Class: 35: Ahead only
Class: 36: Go straight or right
Class: 37: Go straight or left
Class: 38: Keep right
Class: 39: Keep left
Class: 40: Roundabout mandatory
Class: 41: End of no passing
Class: 42: End of no passing by vehicles over 3.5 metric tons

Augment and preprocess data

In [196]:
X_augmented, y_augmented =  augmentDataSet(X_train, y_train)
X_augmented_processed = preprocessDataSet(X_augmented)

X_valid_processed = preprocessDataSet(X_valid)

print(X_augmented_processed.shape)
nr_channels = X_augmented_processed[0].shape[2]
(173995, 32, 32, 3)

Model Architecture

In [197]:
### Define your architecture here.
### Feel free to use as many code cells as needed.

import tensorflow as tf
from tensorflow.contrib.layers import flatten

def CNNNet(x, input_channels, nr_classes, is_training):    
    # Arguments used for tf.truncated_normal, randomly defines variables for the weights and biases for each layer
    mu = 0
    sigma = 0.1
    keep_prob = 0.9
    nr_conv1_filters = 6
    
    # Layer 1: Convolutional. Input = 32x32xinput_channels. Output = 28x28xnr_conv1_filters.
    conv1_W = tf.Variable(tf.truncated_normal(shape=(5, 5, input_channels, nr_conv1_filters), mean = mu, stddev = sigma))
    conv1_b = tf.Variable(tf.zeros(nr_conv1_filters))
    conv1   = tf.nn.conv2d(x, conv1_W, strides=[1, 1, 1, 1], padding='VALID') + conv1_b

    # Activation.
    conv1_activation = tf.nn.relu(conv1)

    # Pooling. Input = 28x28xnr_conv1_filters. Output = 14x14xnv_conv1_filters.
    conv1_pool = tf.nn.max_pool(conv1_activation, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')

    # Apply Dropout
    conv1_dropout = tf.cond(is_training, lambda: tf.nn.dropout(conv1_pool, keep_prob), lambda: conv1_pool)

    # Layer 2: Convolutional. Output = 10x10xnr_conv2_filters.
    nr_conv2_filters = 16
    
    conv2_W = tf.Variable(tf.truncated_normal(shape=(5, 5, nr_conv1_filters, nr_conv2_filters), mean = mu, stddev = sigma))
    conv2_b = tf.Variable(tf.zeros(nr_conv2_filters))
    conv2   = tf.nn.conv2d(conv1_dropout, conv2_W, strides=[1, 1, 1, 1], padding='VALID') + conv2_b
    
    # Activation.
    conv2_activation= tf.nn.relu(conv2)

    # Pooling. Input = 10x10xnr_conv2_filters. Output = 5x5xnr_conv2_filters.
    conv2_pool = tf.nn.max_pool(conv2_activation, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
    # Apply Dropout
    conv2_dropout = tf.cond(is_training, lambda: tf.nn.dropout(conv2_pool, keep_prob), lambda: conv2_pool)
 
    # Flatten. Input = 5x5xnr_conv2_filters. Output = 25xnr_conv2_filters.
    fc0   = tf.concat([flatten(conv2_dropout), flatten(conv1_dropout)], axis = 1)
    
    # Layer 3: Fully Connected. Input = 25xnr_conv2_filters + 14x14xnr_conv1_filters. Output = nr_classes * 4.
    fc0_size = 5*5*nr_conv2_filters + 14*14*nr_conv1_filters
    fc1_size = nr_classes * 4
    fc1_W = tf.Variable(tf.truncated_normal(shape=(fc0_size, fc1_size), mean = mu, stddev = sigma))
    fc1_b = tf.Variable(tf.zeros(fc1_size))
    fc1   = tf.matmul(fc0, fc1_W) + fc1_b
    
    # Activation.
    fc1_activation = tf.nn.relu(fc1)
    # Apply Dropout
    fc1_dropout = tf.cond(is_training, lambda: tf.nn.dropout(fc1_activation, keep_prob), lambda: fc1_activation)
    
    # Layer 4: Fully Connected. Input = fc1_size. Output = nr_classes * 2.
    fc2_size = nr_classes * 2
    fc2_W  = tf.Variable(tf.truncated_normal(shape=(fc1_size, fc2_size), mean = mu, stddev = sigma))
    fc2_b  = tf.Variable(tf.zeros(fc2_size))
    fc2    = tf.matmul(fc1_dropout, fc2_W) + fc2_b
    
    # Activation.
    fc2_activation    = tf.nn.relu(fc2)
    
    # Apply Dropout
    fc2_dropout = tf.cond(is_training, lambda: tf.nn.dropout(fc2_activation, keep_prob), lambda: fc2_activation)
    
    # Layer 5: fully connected:
    fc3_W  = tf.Variable(tf.truncated_normal(shape=(fc2_size, nr_classes), mean = mu, stddev = sigma))
    fc3_b  = tf.Variable(tf.zeros(nr_classes))
    logits    = tf.matmul(fc2_dropout, fc3_W) + fc3_b
    
    # Activation.

    return (logits, fc2_dropout, fc2_activation, fc2,
            fc1_dropout, fc1_activation, fc1,
            conv2_dropout, conv2_pool, conv2_activation, conv2,
            conv1_dropout, conv1_pool, conv1_activation, conv1)

            
In [198]:
x = tf.placeholder(tf.float32, (None, 32, 32, nr_channels))
y = tf.placeholder(tf.int32, (None))
is_training = tf.placeholder(tf.bool)
one_hot_y = tf.one_hot(y, nr_classes)

learning_rate = tf.placeholder(tf.float32)

(logits, fc2_dropout, fc2_activation, fc2,
            fc1_dropout, fc1_activation, fc1,
            conv2_dropout, conv2_pool, conv2_activation, conv2,
            conv1_dropout, conv1_pool, conv1_activation, conv1) = CNNNet(x, nr_channels, nr_classes, is_training)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=one_hot_y)
loss_operation = tf.reduce_mean(cross_entropy)
optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate)
training_operation = optimizer.minimize(loss_operation)

Train, Validate and Test the Model

A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.

In [199]:
from sklearn.utils import shuffle

### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected, 
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.

correct_prediction = tf.equal(tf.argmax(logits, 1), tf.argmax(one_hot_y, 1))
accuracy_operation = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

def evaluate(sess, X_data, y_data):
    num_examples = len(X_data)
    total_accuracy = 0
    for offset in range(0, num_examples, BATCH_SIZE):
        batch_x, batch_y = X_data[offset:offset+BATCH_SIZE], y_data[offset:offset+BATCH_SIZE]
        accuracy = sess.run(accuracy_operation, feed_dict={x: batch_x, y: batch_y, is_training: False})
        total_accuracy += (accuracy * len(batch_x))
    return total_accuracy / num_examples


EPOCHS = 300
BATCH_SIZE = 8192
In [201]:
with tf.Session() as sess:
    saver = tf.train.Saver()
    sess.run(tf.global_variables_initializer())
    num_examples = len(X_augmented_processed)
    
    print("Training...")
    print()
    for i in range(EPOCHS):
        rate = 0.001
        if i > 100:
            rate = 0.001
        if i > 200:
            rate = 0.0001
        X_augmented_processed, y_augmented = shuffle(X_augmented_processed, y_augmented)
        for offset in range(0, num_examples, BATCH_SIZE):
            end = offset + BATCH_SIZE
            batch_x, batch_y = X_augmented_processed[offset:end], y_augmented[offset:end]
            sess.run(training_operation, feed_dict={
                x: batch_x, y: batch_y, is_training: True,
                learning_rate: rate
            })
        
        if i % 10 == 0:
            print("EPOCH {} ...".format(i+1))
            training_accuracy = evaluate(sess, X_augmented_processed, y_augmented)
            print("Training Accuracy = {:.5f}".format(training_accuracy))
            validation_accuracy = evaluate(sess, X_valid_processed, y_valid)
            print("Validation Accuracy = {:.5f}".format(validation_accuracy))
            print()
            saver.save(sess, './cnnnet', global_step = i + 1)
        
    saver.save(sess, './cnnnet')
    print("Model saved")
    
    
    X_test_processed = preprocessDataSet(X_test)
    test_accuracy = evaluate(sess, X_test_processed, y_test)
    print("Test Accuracy = {:.5f}".format(test_accuracy))
Training...

EPOCH 1 ...
Training Accuracy = 0.34645
Validation Accuracy = 0.33311

EPOCH 11 ...
Training Accuracy = 0.96151
Validation Accuracy = 0.91066

EPOCH 21 ...
Training Accuracy = 0.98876
Validation Accuracy = 0.93673

EPOCH 31 ...
Training Accuracy = 0.99507
Validation Accuracy = 0.94807

EPOCH 41 ...
Training Accuracy = 0.99735
Validation Accuracy = 0.94943

EPOCH 51 ...
Training Accuracy = 0.99872
Validation Accuracy = 0.95011

EPOCH 61 ...
Training Accuracy = 0.99945
Validation Accuracy = 0.95488

EPOCH 71 ...
Training Accuracy = 0.99964
Validation Accuracy = 0.95646

EPOCH 81 ...
Training Accuracy = 0.99983
Validation Accuracy = 0.95828

EPOCH 91 ...
Training Accuracy = 0.99991
Validation Accuracy = 0.95646

EPOCH 101 ...
Training Accuracy = 0.99995
Validation Accuracy = 0.95896

EPOCH 111 ...
Training Accuracy = 0.99997
Validation Accuracy = 0.95760

EPOCH 121 ...
Training Accuracy = 0.99998
Validation Accuracy = 0.95941

EPOCH 131 ...
Training Accuracy = 0.99999
Validation Accuracy = 0.96077

EPOCH 141 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.95941

EPOCH 151 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96259

EPOCH 161 ...
Training Accuracy = 0.99999
Validation Accuracy = 0.95986

EPOCH 171 ...
Training Accuracy = 0.99999
Validation Accuracy = 0.96009

EPOCH 181 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96349

EPOCH 191 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.95850

EPOCH 201 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96032

EPOCH 211 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96236

EPOCH 221 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96191

EPOCH 231 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96281

EPOCH 241 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96304

EPOCH 251 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96100

EPOCH 261 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96327

EPOCH 271 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96349

EPOCH 281 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96259

EPOCH 291 ...
Training Accuracy = 1.00000
Validation Accuracy = 0.96191

Model saved
Test Accuracy = 0.95186

Step 3: Test a Model on New Images

To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.

You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.

Load and Output the Images

In [202]:
### Load the images and plot them here.
### Feel free to use as many code cells as needed.
import skimage.io
import skimage.transform
from skimage.util import dtype

extra_images_data = {
    21: 'double_curve.png',
    40: 'roundabout.png',
    34: 'turn_left.png',
    13: 'yield.png',
    38: 'keep_right.png',
    0: 'speed_20.png',
}

def _prepare_rgba_array(arr):
    """Check the shape of the array to be RGBA and convert it to
    floating point representation.
    """
    arr = np.asanyarray(arr)

    if arr.ndim not in [3, 4] or arr.shape[-1] != 4:
        msg = ("the input array must have a shape == (.., ..,[ ..,] 4)), "
               "got {0}".format(arr.shape))
        raise ValueError(msg)

    return dtype.img_as_float(arr)

def rgba2rgb(rgba, background=(1, 1, 1)):
    arr = _prepare_rgba_array(rgba)
    if isinstance(background, tuple) and len(background) != 3:
        raise ValueError('the background must be a tuple with 3 items - the '
                         'RGB color of the background. Got {0} items.'
                         .format(len(background)))

    alpha = arr[..., -1]
    channels = arr[..., :-1]
    out = np.empty_like(channels)

    for ichan in range(channels.shape[-1]):
        out[..., ichan] = np.clip(
            (1 - alpha) * background[ichan] + alpha * channels[..., ichan],
            a_min=0, a_max=1)
    return out

extra_images = []
extra_labels = []
for label, image_file in extra_images_data.items():
    image = skimage.io.imread('downloaded_signs/%s' % image_file)
    image = skimage.transform.resize(image, (32, 32))
    image = rgba2rgb(image)
    extra_images.extend([image])
    extra_labels.extend([label])

extra_images = np.asarray(extra_images)
extra_labels = np.asarray(extra_labels)
    
plotRandomSamples(extra_images, extra_labels, 1)
Class: 0: Speed limit (20km/h)
Class: 13: Yield
Class: 21: Double curve
Class: 34: Turn left ahead
Class: 38: Keep right
Class: 40: Roundabout mandatory

Predict the Sign Type for Each Image

In [203]:
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.

extra_images_processed = preprocessDataSet(extra_images)

with tf.Session() as sess:
    saver = tf.train.Saver()
    saver.restore(sess, './cnnnet')

    nr_samples = len(extra_images_processed)
    predictions_result = sess.run(tf.argmax(tf.nn.softmax(logits), 1), feed_dict={
        x: extra_images_processed[0:nr_samples],
        y: extra_labels[0:nr_samples],
        is_training: False
    })
    correct_predictions_results = sess.run(correct_prediction, feed_dict={
        x: extra_images_processed[0:nr_samples],
        y: extra_labels[0:nr_samples],
        is_training: False
    })
    softmax_result = sess.run(tf.nn.softmax(logits), feed_dict={
        x: extra_images_processed[0:nr_samples],
        y: extra_labels[0:nr_samples],
        is_training: False
    })
    top_k_softmax = sess.run(tf.nn.top_k(tf.nn.softmax(logits), k=5), feed_dict={
        x: extra_images_processed[0:nr_samples],
        y: extra_labels[0:nr_samples],
        is_training: False
    })
    

Analyze Performance

In [204]:
### Calculate the accuracy for these 5 new images. 
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print("Actual labels:    %s" % extra_labels)
print("Predicted labels: %s" % predictions_result)

correct_count = 0
for (a,p) in zip(extra_labels, predictions_result):
    if a == p:
        correct_count += 1

print("Accuracy = {:.5f}".format(1.0 * correct_count / len(extra_labels)))
Actual labels:    [ 0 34 21 38 40 13]
Predicted labels: [ 0 34 11 38 40 13]
Accuracy = 0.83333

Output Top 5 Softmax Probabilities For Each Image Found on the Web

For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.

The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.

tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.

Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tk.nn.top_k is used to choose the three classes with the highest probability:

# (5, 6) array
a = np.array([[ 0.24879643,  0.07032244,  0.12641572,  0.34763842,  0.07893497,
         0.12789202],
       [ 0.28086119,  0.27569815,  0.08594638,  0.0178669 ,  0.18063401,
         0.15899337],
       [ 0.26076848,  0.23664738,  0.08020603,  0.07001922,  0.1134371 ,
         0.23892179],
       [ 0.11943333,  0.29198961,  0.02605103,  0.26234032,  0.1351348 ,
         0.16505091],
       [ 0.09561176,  0.34396535,  0.0643941 ,  0.16240774,  0.24206137,
         0.09155967]])

Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:

TopKV2(values=array([[ 0.34763842,  0.24879643,  0.12789202],
       [ 0.28086119,  0.27569815,  0.18063401],
       [ 0.26076848,  0.23892179,  0.23664738],
       [ 0.29198961,  0.26234032,  0.16505091],
       [ 0.34396535,  0.24206137,  0.16240774]]), indices=array([[3, 0, 5],
       [0, 1, 4],
       [0, 5, 1],
       [1, 3, 5],
       [1, 4, 3]], dtype=int32))

Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.

In [205]:
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web. 
### Feel free to use as many code cells as needed.
print (top_k_softmax)
TopKV2(values=array([[  9.09472525e-01,   9.05273408e-02,   1.00598818e-07,
          2.78746093e-08,   1.68915182e-09],
       [  1.00000000e+00,   5.67351606e-08,   7.80538882e-13,
          3.73052080e-14,   1.10085696e-14],
       [  9.52687442e-01,   4.61670980e-02,   1.00169191e-03,
          1.02722333e-04,   4.02699370e-05],
       [  1.00000000e+00,   2.69040478e-17,   1.58684013e-18,
          2.20687309e-22,   7.27828956e-26],
       [  1.00000000e+00,   2.58587777e-16,   5.10509378e-20,
          1.14651143e-20,   1.34825310e-21],
       [  1.00000000e+00,   8.94058777e-15,   9.79277786e-18,
          3.13628088e-19,   1.16772105e-19]], dtype=float32), indices=array([[ 0,  1,  5, 16,  2],
       [34, 35, 33, 40, 38],
       [11, 21, 23, 25, 24],
       [38, 36, 34, 40, 39],
       [40, 33, 37,  2, 11],
       [13, 15,  9, 12,  3]], dtype=int32))

Step 4: Visualize the Neural Network's State with Test Images

This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.

Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.

For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.

Combined Image

Your output should look something like this (above)

In [241]:
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.

# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry

def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
    # Here make sure to preprocess your image_input in a way your network expects
    # with size, normalization, ect if needed
    # image_input =
    # Note: x should be the same name as your network's tensorflow data placeholder variable
    # If you get an error tf_activation is not defined it maybe having trouble accessing the variable from inside a function
    #activation = tf_activation.eval(session=sess,feed_dict={x : image_input, is_training: False})
    activation = sess.run(tf_activation, feed_dict={x : image_input, is_training: False})
    featuremaps = activation.shape[3]
    plt.figure(plt_num, figsize=(50,50))
    for featuremap in range(featuremaps):
        plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
        plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
        if activation_min != -1 & activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
        elif activation_max != -1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
        elif activation_min !=-1:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
        else:
            plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
    plt.show()
            
#(logits, fc2_dropout, fc2_activation, fc2,
#            fc1_dropout, fc1_activation, fc1,
#            conv2_dropout, conv2_pool, conv2_activation, conv2,
#            conv1_dropout, conv1_pool, conv1_activation, conv1)

with tf.Session() as sess:
    saver = tf.train.Saver()
    saver.restore(sess, './cnnnet')
    for i in range(len(extra_images_processed)):
        image = extra_images_processed[i:i+1]
        outputFeatureMap(image, conv1)
        outputFeatureMap(image, conv1_activation)
        outputFeatureMap(image, conv1_pool)
        outputFeatureMap(image, conv1_dropout)
        outputFeatureMap(image, conv2)
        outputFeatureMap(image, conv2_activation)
        outputFeatureMap(image, conv2_pool)
        outputFeatureMap(image, conv2_dropout)
    

Question 9

Discuss how you used the visual output of your trained network's feature maps to show that it had learned to look for interesting characteristics in traffic sign images

Answer:

The result of the first convolution layer for all of the images before activation (except wrongly classified) clearly indicate that convolution removed all "insignificant" parts of the sign, except the ones clearly identifying the class of the sign.

Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.

Project Writeup

Once you have completed the code implementation, document your results in a project writeup using this template as a guide. The writeup can be in a markdown or pdf file.